// pages/myself/edit-info/editInfo.js
const app = getApp()
const { validate } = require('../../../utils/validator.js')
const validator = (name, rule, value, callback) => {
  const reg = /^[a-zA-Z\u4e00-\u9fa5]*$/
  console.log(name, rule, value.length > 18)
  if (name === '个人简介标题' && value.length > 18) {
    callback(new Error(`${name}不能超过18个字符`))
  }
  if (!reg.test(value)) {
    callback(new Error(`${name}需为中文或英文字符`))
  } else {
    callback()
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    key: '',
    value: '',
    title: {
      realName: '姓名',
      workTitle: '职位',
      briefTitle: '个人简介标题',
      briefContent: '个人简介'
    },
    rules: {
      realName: [
        { required: true, message: '姓名必填' },
        { validator: (rule, value, callback) => {
            validator('姓名', rule, value, callback)
          } },
      ],
      workTitle: [
        { required: true, message: '职位必填' },
        { validator: (rule, value, callback) => {
          validator('职位', rule, value, callback)
        } },
      ],
      briefTitle: [
        { validator: (rule, value, callback) => {
          validator('个人简介标题', rule, value, callback)
        } },
      ],
      briefContent: [
        { validator: (rule, value, callback) => {
          validator('个人简介', rule, value, callback)
        } },
      ]
    },
    loading: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      key: options.key,
      value: options.value,
      id: options.id
    })
    wx.setNavigationBarTitle({
      title: `修改${this.data.title[options.key]}`
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  edit: function () {
    const { key, value, id } = this.data
    let data = {
      id
    }
    data[key] = value
    validate(key, this.data.rules[key], value, (valid) => {
      if (valid) {
        this.setData({
          loading: true
        })
        app.api.post({
          url: 'cpic_user_update',
          data
        }).then(res => {
          wx.navigateBack()
        }).finally(() => {
          this.setData({
            loading: false
          })
        })
      }
    })
  }
})